<template>
  <el-card>
    <template #header>
      <h2>添加账号</h2>
    </template>
    <template>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="uname">
          <el-input v-model="ruleForm.uname"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户组">
          <el-select v-model="ruleForm.userGroup" placeholder="请选择用户组">
            <el-option label="普通管理员" value="普通管理员"> </el-option>
            <el-option label="超级管理员" value="超级管理员"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >添加</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-card>
</template>
<script>
import { checkuName, validatePass } from '../../utils/validate.js'
import { addUser } from '../../api/users.js'
export default {
  data() {
    return {
      ruleForm: {
        uname: '',
        pass: '',
        userGroup: ''
      },
      rules: {
        uname: [{ validator: checkuName, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }]
      },
      form: {
        region: ''
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          //当表单验证通过 则可以发起请求
          const { code, msg } = await addUser({
            account: this.ruleForm.uname,
            password: this.ruleForm.pass,
            userGroup: this.ruleForm.userGroup
          })
          if (code === 0) {
            this.$message({
              message: msg,
              type: 'success'
            })
            // / 清空本地数据，并跳转到账号列表
            this.resetForm('ruleForm')
            setTimeout(() => {
              this.$router.push('/Account/index')
            }, 1500)
          }
        } else {
          this.$message.error('你咋啥都不填呢！！！')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.el-input {
  width: 240px;
}
</style>
